package com.qf.base;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DataSourceAspect {
//        @Before("@annotation(QFDataSource)")
//        public void switchDataSource(JoinPoint point) {
//            MethodSignature signature = (MethodSignature) point.getSignature();
//            Method method = signature.getMethod();
//            QFDataSource dataSource = method.getAnnotation(QFDataSource.class);
//            System.out.println("--------------------------");
//            System.out.println(dataSource.value());
//            System.out.println("--------------------------");
//            if (dataSource != null) {
//                DynamicDataSourceContextHolder.setDataSourceType(dataSource.value());
//            }else {
//                DynamicDataSourceContextHolder.getDataSourceType();
//            }
//        }
        @Around("@annotation(QFDataSource)")
        public Object switchDataSource(ProceedingJoinPoint joinPoint) throws Throwable {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            QFDataSource dataSource = method.getAnnotation(QFDataSource.class);
            try {
                if (dataSource != null) {
                    DynamicDataSourceContextHolder.setDataSourceType(dataSource.value());
                    System.out.println("------------------------------");
                    System.out.println(dataSource.value());
                    System.out.println("------------------------------");
                 }
                Object proceed = joinPoint.proceed();
                return proceed;
            } catch (Exception e){
                // 还原回主库
                System.out.println("=================hhh====================");
                e.printStackTrace();
                // DynamicDataSourceContextHolder.clearDataSourceType();
            }
            return joinPoint.proceed();
        }
}